package com.wanyangproject.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.wanyangproject.net.HttpUtil;
import com.wanyangproject.net.util.ACache;
import com.wanyangproject.net.util.AppSession;


public abstract class BaseFragment extends Fragment {
    protected Context mContext;
    protected Activity mActivity;
    protected InputMethodManager inputMethodManager;
    protected AppSession mSession;
    protected HttpUtil mHttpUtil;
    private View rootView;
    protected ACache mCache;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        mActivity = getActivity();
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        mSession = AppSession.getInstance(mContext);
//        mHttpUtil = HttpUtil.getInstance();
        mCache = ACache.get(mContext);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null){
            if (getContentResId() != 0) {
                rootView = inflater.inflate(getContentResId(), container, false);
            } else {
                rootView = super.onCreateView(inflater, container, savedInstanceState);
            }
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
        mSession = null;
    }

    public <T> T findViewById(int id) {
        T view = (T) rootView.findViewById(id);
        return view;
    }

    public abstract int getContentResId();
    public abstract void init();
}
